package com.fly.core.aop;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * aop 打印运行时间
 * 
 * @author 00fly
 * @version [版本号, 2018年12月2日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Aspect
@Component
public class RunTimeAspect
{
    @Autowired
    DruidDataSource dataSource;
    
    @Around("within(com.fly.demo..*)")
    public Object around(ProceedingJoinPoint joinPoint)
        throws Throwable
    {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = new StringBuffer(className).append(".").append(method.getName()).toString();
        boolean isController = method.isAnnotationPresent(RequestMapping.class) || method.isAnnotationPresent(GetMapping.class) || method.isAnnotationPresent(PostMapping.class);
        if (isController)
        {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            request.setAttribute("jdbcUrl", dataSource.getRawJdbcUrl());
            StringBuilder url = new StringBuilder(request.getRequestURI());
            String query = request.getQueryString();
            if (query != null && query.length() > 0)
            {
                url.append("?").append(query);
            }
            log.info("★★★★★★★★ start visit url = {}", url);
        }
        StopWatch clock = new StopWatch();
        clock.start(methodName);
        Object object = joinPoint.proceed();
        clock.stop();
        log.info("running {} ms, method = {}", clock.getTotalTimeMillis(), clock.getLastTaskName());
        return object;
    }
    
    @AfterReturning("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void afterReturing(JoinPoint joinPoint)
    {
        log.info("running @AfterReturning");
    }
}
